var app = angular.module('BaseServer');

//我们把socket服务定义成了一个factory，这样它只会被实例化一次，而且在整个应用的作用域范围内就成为了一个单例
app.factory('PublicSocket', ['BaseService', function(BaseService) {
	return function(){
		this.Socket = null;
		var self = this;
		BaseService.getSysParameterValue('002', function(data){
            self.Socket = io.connect('http://' + document.location.hostname + ":" + data);
        });

		//监听接收消息
		this.on = function(eventName, callback){
			if(this.Socket) {
				this.Socket.on(eventName, function(data){
					callback(data);
				});
			}
			else{
				var newErr = {
                    leval: 5,
                    title: 'Socket连接失败',
                    message: 'Socket连接失败，请检查服务器是否正常'
                }
                PublicFunction.errFun(newErr);
			}
		};
		//发送消息
		this.emit = function(eventName, data) {
			if (this.Socket) {
				this.Socket.emit(eventName, data);
			}
		};
		//发给自己
		this.toSelf = function(eventName, sendData) {
	      if (this.Socket) {
	      	var data = {
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.Socket.emit("toSelf", data);
	      }
    	};
    	//发给除自己的所有人
    	this.toOther = function(eventName, sendData) {
	      if (this.Socket) {
	      	var data = {
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.Socket.emit("toOther", data);
	      }
    	};
    	//发给所有人，包括自己
    	this.toAll = function(eventName, sendData) {
	      if (this.Socket) {
	      	var data = {
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.Socket.emit("toAll", data);
	      }
    	};
    	//加入房间
    	this.joinRoom = function(roomName) {
	      if (this.Socket) {
	      	var data = {
	      		RoomName: roomName
	      	};
	        this.Socket.emit("joinRoom", data);
	      }
    	};
    	//离开房间
    	this.leaveRoom = function(roomName) {
	      if (this.Socket) {
	      	var data = {
	      		RoomName: roomName
	      	};
	        this.Socket.emit("leaveRoom", data);
	      }
    	};
    	//向指定房间发送消息，不包括自己
    	this.toRoom = function(roomName, eventName, sendData) {
	      if (this.Socket) {
	      	var data = {
	      		RoomName: roomName,
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.Socket.emit("toRoom", data);
	      }
    	};
    	//向指定房间发送消息，包括自己
    	this.inRoom = function(roomName, eventName, sendData) {
	      if (this.Socket) {
	      	var data = {
	      		RoomName: roomName,
	      		EventName: eventName,
	      		Data: sendData
	      	};
	        this.Socket.emit("inRoom", data);
	      }
    	};
    	this.disconnect = function(){
    		this.Socket.emit("clientDisconnect");
    	};
	};
}]);